﻿@{
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/Content/upload.css" type="text/css" rel="stylesheet" />

    <style>
        #map-canvas
        {
            height: 200px;
            width: 400px;
            margin-left: 30px;
            padding: 0px;
            float: left;
        }
    </style>
    <script>
        $(function () {
            var imageUploadField = 'SiteThumbImg';
            var uploaderUrl = '/AdvtAdmin/Upload';
            var valueField = 'SiteThumb';
            var buttonImage = '/images/upload.png';
            var isSignalImage = true;
            var imgDiv = 'div_img_list';
            UploadImage(imageUploadField, valueField, uploaderUrl, buttonImage, isSignalImage, imgDiv);

            var imageUploadFieldGallery = 'SiteGallery';
            var uploaderUrlGallery = '/AdvtAdmin/Upload';
            var valueFieldGallery = 'SiteGalleryVal';
            var buttonImageGallery = '/images/upload.png';
            var isSignalImageGallery = false;
            var imgDivGallery = 'div_gallery_list';
            UploadImage(imageUploadFieldGallery, valueFieldGallery, uploaderUrlGallery, buttonImageGallery, isSignalImageGallery, imgDivGallery);

            $("#PhoneNumber").mask("(999) 999-9999");

            $('#searchSiteType').combobox({
                url: '/AdvtAdmin/GetSiteType',
                valueField: 'SiteTypeId',
                textField: 'SiteTypeName'
            });
        });

        var url;
        function newAdvt() {
            initData();
            $('#dlg').dialog('open').dialog('setTitle', 'New Advt');
            $('#fm').form('clear');
            $("#div_img_list").html('');
            $("#div_gallery_list").html('');
            initialize();
            url = '/AdvtAdmin/AddNewAdvt';
        }
        function editAdvt() {
            var row = $('#dg').datagrid('getSelected');
            if (row) {
                $('#dlg').dialog('open').dialog('setTitle', 'Edit Advt');
                initData(row);
                $('#fm').form('load', row);
                initialize();
                url = '/AdvtAdmin/UpdateAdvt';
            }
            else {
                $.messager.alert("Message", "Please select one record.");
            }
        }
        function saveAdvt() {
            if ($("#SiteThumb").val() === '') {
                $("#spanThumb").show();
                return;
            } else {
                $("#spanThumb").hide();
            }
            if ($("#SiteGalleryVal").val() === '' || $("#SiteGalleryVal").val().split(',').length < 4) {
                $("#spanGallery").show();
                return;
            }
            else {
                $("#spanGallery").hide();
            }
            var postdata = {
                AdvtSiteId: $("#AdvtSiteId").val(),
                SiteName: $("#SiteName").val(),
                SiteDescription: $("#SiteDescription").val(),
                SiteTypeId: $("#SiteTypeId").combobox('getValue'),//SiteTypeId: $("#SiteTypeId").val(),
                Address: $("#Address").val(),
                longitude: $("#longitude").val(),
                latitude: $("#latitude").val(),
                SiteURL: $("#SiteURL").val(),
                SiteAmount: $("#SiteAmount").val(),
                PhoneNumber: $("#PhoneNumber").val(),
                //SiteRate: $("#SiteRate").val(),
                SiteThumb: $("#SiteThumb").val(),
                SiteGallery: $("#SiteGalleryVal").val().split(','),
                CountryId: $("#CountryId").combobox('getValue'),//$("#CountryId").val()
                CardAccepted: $("#CardAccepted").combobox('getValues'),
                CashAccepted: $("#CashAccepted").combobox('getValues')
            };

            $.ajax({
                type: "POST",
                url: url,
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(postdata),
                beforeSend: function () {
                    return $('#fm').form('validate');
                },
                success: function (result) {
                    if (result.Success) {
                        $.messager.alert("Message", result.Message);
                        $('#dlg').dialog('close');        // close the dialog
                        $('#dg').datagrid('reload');    // reload the user data
                        $("#div_img_list").html('');
                        $("#div_gallery_list").html('');

                    } else {
                        $.messager.alert("Message", result.Message);
                    }

                }
            });
        }
        function destroyAdvt() {
            var row = $('#dg').datagrid('getSelected');
            if (row) {
                $.messager.confirm('Confirm', 'Are you sure you want to destroy this record?', function (r) {
                    if (r) {
                        $.post('/AdvtAdmin/DeleteAdvt', { id: row.AdvtSiteId }, function (result) {
                            if (result == "success") {
                                $.messager.alert("Message", "Delete Successfully");
                                $('#dg').datagrid('reload');    // reload the user data
                            } else {
                                $.messager.show({    // show error message
                                    title: 'Error',
                                    msg: 'Please contact the admin for support'//result.errorMsg
                                });
                            }
                        }, 'text');
                    }
                });
            }
            else {
                $.messager.alert("Message", "Please select one record.");
            }
        }
        function loadType() {
            $('#SiteTypeId').combobox({
                url: '/AdvtAdmin/GetSiteType',
                valueField: 'SiteTypeId',
                textField: 'SiteTypeName'
            });
        }
        function loadCountry() {
            $('#CountryId').combobox({
                url: '/AdvtAdmin/GetCountry',
                valueField: 'CountryId',
                textField: 'CountryName'
            });
        }
        function loadCards() {
            $('#CardAccepted').combobox('reload', '/AdvtAdmin/GetCards');
        }
        function loadCashType() {
            $('#CashAccepted').combobox('reload', '/AdvtAdmin/GetCashType');
        }
        function initData(row) {
            if (row) {
                var imageSrc = row['SiteThumb'];
                $("#div_img_list").html('<img alt="" src="' + imageSrc + '" height="32px" width="32px" /> ');
                $("#SiteThumb").val(row['SiteThumb']);

                var siteGalleryVal = row['SiteGallery'];
                var galleryHtml = '';
                for (var i = 0; i < siteGalleryVal.length; i++) {
                    galleryHtml += '<div id="div_img_' + siteGalleryVal[i].substr(15, 15) + '"  class="uploading"><img alt="" src="' + siteGalleryVal[i] + '" height="32px" width="32px" />';
                    galleryHtml += "<a href=\"javascript:\" onclick=\"RemoveImg('" + siteGalleryVal[i].substr(15, 15) + "');\">X</a></div>";
                }
                $("#div_gallery_list").html(galleryHtml);
                $("#SiteGalleryVal").val(siteGalleryVal);
                $("#latitude").val(row['latitude']);
                $("#longitude").val(row['longitude']);
            }
            loadType();
            loadCountry();
            loadCards();
            loadCashType();
        }
        function RemoveImg(id) {
            var deleteImgSrc = $("#div_img_" + id).children('img').attr('src');
            var siteGalleryArr = $("#SiteGalleryVal").val().split(',');;
            siteGalleryArr.pop(deleteImgSrc);
            $("#SiteGalleryVal").val(siteGalleryArr);
            $("#div_img_" + id).remove();
        }
        function searchAdvt() {
            $('#dg').datagrid('load', {
                SiteName: $('#txtSiteName').val(),
                SiteTypeId: $('#searchSiteType').combobox('getValue')
            });
        }
        function cellStyler(value, row, index) {
            return '<a id="viewPromotion"  href="javascript:void(0)" plain="true" onClick="viewPromotions(' + value + ')"> View/Edit </a>';
        }
        function viewPromotions(advtId) {
            var title = 'View Promotions - Advt ID:' + advtId;
            var content = '<iframe id="frmWorkArea" width="100%" height="95%" frameborder="0" scrolling="yes" src="/PromotionAdmin/Index/' + advtId + '"></iframe>';
            self.parent.addTab(title, content);
        }
    </script>
</head>
<body>
    <table id="dg" title="Site Admin" class="easyui-datagrid" style="height: 500px"
        url="/AdvtAdmin/GetAllAdvt"
        toolbar="#toolbar" pagination="true" iconcls="icon-ok"
        rownumbers="true" fitcolumns="true" singleselect="true">
        <thead>
            <tr>
                @*<th field="AdvtSiteId" width="50" hidden="true">AdvtSiteId</th>*@
                <th field="SiteName" width="50">Name</th>
                <th field="SiteDescription" width="50">Description</th>
                <th field="PhoneNumber" width="50">Contact Phone</th>
                <th field="SiteAmount" width="50">Available</th>
                <th field="SiteRate" width="50">Rating</th>
                <th field="SiteTypeName" width="50">Type</th>
                @*<th field="CountryName" width="30">Country</th>*@
                <th field="Promotions" width="50">Promotions</th>
                <th field="Address" width="50" hidden="true">Address</th>
                <th field="SiteThumb" width="50" hidden="true">SiteThumb</th>
                <th field="CardAccepted" width="50" hidden="true">CardAccepted</th>
                <th field="CashAccepted" width="50" hidden="true">CashAccepted</th>
                <th field="longitude" width="50" hidden="true">longitude</th>
                <th field="latitude" width="50" hidden="true">latitude</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar" style="padding: 5px; height: auto">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="newAdvt()">New Site</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-edit" plain="true" onclick="editAdvt()">Edit Site</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-remove" plain="true" onclick="destroyAdvt()">Remove Site</a>
        <div>
            Site Name:
            <input id="txtSiteName" style="width: 150px">
            &nbsp;&nbsp;&nbsp;&nbsp;
            Site Type:
            <input class="easyui-combobox" type="text" id="searchSiteType" name="SiteTypeId" />
            <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="searchAdvt()">Search</a>
        </div>
    </div>
    <div id="dlg" class="easyui-dialog" style="width: 550px; height: 520px; padding: 10px 20px"
        closed="true" modal="true" buttons="#dlg-buttons">
        <div class="ftitle">Site Information</div>
        <form id="fm" method="post" novalidate>
            <input id="AdvtSiteId" name="AdvtSiteId" type="hidden">
            <div class="fitem">
                <label>Name:</label>
                <input id="SiteName" name="SiteName" class="easyui-validatebox" required="true">
            </div>
            <div class="fitem">
                <label>Description:</label>
                <textarea id="SiteDescription" name="SiteDescription" style="height: 30px;"></textarea>
            </div>
            <div class="fitem">
                <label>Type:</label>
                <input class="easyui-combobox" type="text" id="SiteTypeId" name="SiteTypeId" required="true" />
            </div>

            <div class="fitem">
                <label>Address:</label>
                <input id="longitude" name="longitude" type="hidden">
                <input id="latitude" name="latitude" type="hidden">
                <input id="Address" name="Address">
                <input type="button" value="Search" onclick="codeAddress()">
            </div>
            <div id="map-canvas">
            </div>
            <div class="fitem">
                <label>URL:</label>
                <input id="SiteURL" name="SiteURL" class="easyui-validatebox" validtype="url">
            </div>
            <div class="fitem">
                <label>Balance:</label>
                <input id="SiteAmount" name="SiteAmount" class="easyui-numberbox" data-options="precision:2,required:true">
            </div>
            <div class="fitem">
                <label>Contact Phone:</label>
                <input id="PhoneNumber" name="PhoneNumber">
            </div>
            <div class="fitem">
                <label>Site Thumb: <span style="font-size: 10px; color: #808080">(Advice Size: 500X500)</span></label>
                <div id="div_img_list"></div>
                <input id="SiteThumbImg" name="SiteThumbImg" type="file">
                <div id="spanThumb" style="display:none;">
                    <span style="font-size: 12px; color: #EE1209">Required</span>
                </div>
                <input id="SiteThumb" type="hidden">
            </div>
            <div class="fitem">
                <label>Site Gallery: <span style="font-size: 10px; color: #808080">(Advice Size: 1024X420)</span></label>
                <div id="div_gallery_list"></div>
                <input id="SiteGallery" name="SiteGallery" type="file">
                <div id="spanGallery" style="display:none;">
                    <span style="font-size: 12px; color: #EE1209">Required at least 4 images.</span>
                </div>
                <input id="SiteGalleryVal" type="hidden">
            </div>
            <div class="fitem">
                <label>Card Accepted:</label>
                <input class="easyui-combobox"
                    name="CardAccepted" id="CardAccepted" required="true"
                    data-options="
                            valueField:'CardTypeId',
                            textField:'CardTypeName',
                            multiple:true,
                            panelHeight:'auto'
                    ">
            </div>
            <div class="fitem">
                <label>Cash Accepted:</label>
                <input class="easyui-combobox"
                    name="CashAccepted" id="CashAccepted" required="true"
                    data-options="
                            valueField:'CashTypeId',
                            textField:'CashTypeName',
                            multiple:true,
                            panelHeight:'auto'
                    ">
            </div>
            <div class="fitem">
                <label>Country:</label>
                <input class="easyui-combobox" type="text" id="CountryId" name="CountryId" required="true" />
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="saveAdvt()">Save</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#dlg').dialog('close');">Cancel</a>
    </div>
</body>
</html>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
    var geocoder = new google.maps.Geocoder();
    var map;
    var markers = [];
    function geocodePosition(pos) {
        geocoder.geocode({
            latLng: pos
        }, function (responses) {
            if (responses && responses.length > 0) {
                updateMarkerAddress(responses[0].formatted_address);
            } else {
                updateMarkerAddress('Cannot determine address at this location.');
            }
        });
    }

    // Add a marker to the map and push to the array.
    function addMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            draggable: true
        });
        clearMarkers();
        markers.push(marker);
        return marker;
    }

    // Sets the map on all markers in the array.
    function setAllMap(map) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setAllMap(null);
    }

    // Shows any markers currently in the array.
    function showMarkers() {
        setAllMap(map);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
        markers = [];
    }

    function updateMarkerStatus(str) {
        document.getElementById('markerStatus').innerHTML = str;
    }

    function updateMarkerPosition(latLng) {
        $('#latitude').val(latLng.lat());
        $('#longitude').val(latLng.lng());
    }

    function updateMarkerAddress(str) {
        document.getElementById('Address').value = str;
    }

    function initialize() {
        var address = document.getElementById('Address').value;
        if (address === '')
            address = 'Jinan, Shandong, China';
        var marker;
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map = new google.maps.Map(document.getElementById('map-canvas'), {
                    zoom: 12,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                });

                marker = addMarker(results[0].geometry.location);
                // Add dragging event listeners.
                google.maps.event.addListener(marker, 'dragstart', function () {
                    //updateMarkerAddress('Dragging...');
                });

                google.maps.event.addListener(marker, 'drag', function () {
                    //updateMarkerStatus('Dragging...');
                    updateMarkerPosition(marker.getPosition());
                });

                google.maps.event.addListener(marker, 'dragend', function () {
                    //updateMarkerStatus('Drag ended');
                    updateMarkerPosition(marker.getPosition());
                    geocodePosition(marker.getPosition());
                });
            }
        });
    }

    //code address to LatLng via googlemaps
    function codeAddress() {
        var marker;
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById('Address').value;
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                $('#latitude').val(results[0].geometry.location.lat());
                $('#longitude').val(results[0].geometry.location.lng());

                map.setCenter(results[0].geometry.location);
                marker = addMarker(results[0].geometry.location);
                map.setZoom(12);
                // Add dragging event listeners.
                google.maps.event.addListener(marker, 'dragstart', function () {
                    //updateMarkerAddress('Dragging...');
                });

                google.maps.event.addListener(marker, 'drag', function () {
                    //updateMarkerStatus('Dragging...');
                    updateMarkerPosition(marker.getPosition());
                });

                google.maps.event.addListener(marker, 'dragend', function () {
                    //updateMarkerStatus('Drag ended');
                    updateMarkerPosition(marker.getPosition());
                    geocodePosition(marker.getPosition());
                });
            }
        });
    }
</script>
